package com;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created by apple on 17/9/28.
 */
public class DemoThread {
//    public static void main(String[] args) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
////                int i = 0;
//
//                for (int i = 0; i < 500000; i++) {
//                    if (Thread.currentThread().interrupted()) {
//                        System.out.println("should be stopped and exit");
//                        break;
//                    }
//                    System.out.println("i=" + (i + 1));
//                }
////                while (true){
////                    i++;
////                    System.out.println(1);
////
//////                    if(i == 100){
//////                        System.out.println(Thread.currentThread().isInterrupted());
//////                    }
////                }
//            }
//        }).start();
////        MyThread m = new MyThread();
////        m.run();
//
//        Thread t = new Thread(new Callable());
//    }
//
//
//
//    public static class MyThread extends Thread {
//        @Override
//        public void run() {
//            super.run();
//            try{
//                for (int i = 0; i < 500000; i++) {
//                    if (this.interrupted()) {
//                        System.out.println("should be stopped and exit");
//                        throw new InterruptedException();
//                    }
//                    System.out.println("i=" + (i + 1));
//                }
//                System.out.println("this line cannot be executed. cause thread throws exception");//这行语句不会被执行!!!
//            }catch(InterruptedException e){
//                System.out.println("catch interrupted exception");
//                e.printStackTrace();
//            }
//        }
//    }

    public static void main(String[] args) {
        Callable<Integer> callable = new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };
        FutureTask<Integer> future = new FutureTask<Integer>(callable);
        new Thread(future).start();
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
